package com.mindskip.xzs.security;

import com.mindskip.xzs.domain.enums.SystemCode;
import com.mindskip.xzs.domain.entity.UserEventLog;
import com.mindskip.xzs.event.UserEvent;
import com.mindskip.xzs.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;


/**
 * 登录成功后调用该方法
 */
@Component
public class RestAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {

    private final ApplicationEventPublisher eventPublisher;
    private final UserService userService;

    @Autowired
    public RestAuthenticationSuccessHandler(ApplicationEventPublisher eventPublisher, UserService userService) {
        this.eventPublisher = eventPublisher;
        this.userService = userService;
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {

        // 从认证成功的 authentication 中获取 User(SpringSecurity中的)
        Object object = authentication.getPrincipal();
        if (null != object) {
            org.springframework.security.core.userdetails.User springSecurityUser = (User) object;
            // 从SpringSecurity中的User获取到用户名，然后去查询数据库得到自定义的User
            com.mindskip.xzs.domain.entity.User user = userService.getUserByUserName(springSecurityUser.getUsername());
            if (null != user) {
                // 设置 UserEventLog
                UserEventLog userEventLog = new UserEventLog(user.getId(), user.getUserName(), user.getRealName(), new Date());
                userEventLog.setContent(user.getUserName() + " 登录了学之思开源考试系统");
                // 发布事件
                eventPublisher.publishEvent(new UserEvent(userEventLog));
                com.mindskip.xzs.domain.entity.User newUser = new com.mindskip.xzs.domain.entity.User();
                newUser.setUserName(user.getUserName());
                newUser.setImagePath(user.getImagePath());
                RestUtil.response(response, SystemCode.OK.getCode(), SystemCode.OK.getMessage(), newUser);
            }
        } else {
            RestUtil.response(response, SystemCode.UNAUTHORIZED.getCode(), SystemCode.UNAUTHORIZED.getMessage());
        }
    }
}
